#!/bin/bash
cd ~/app-root/data/temp/tool/
base="http://live.funtownlife.com/OpenAPI/v1"
device="ONEPLUS%20A3010"
useragent="--user-agent \"okhttp/3.2.0\""

login(){
    email=$1
    password=$2
    echo "开始登录账号：$(echo $email|sed 's#%40#@#')"
    logindata=$(curl -s "$base/auth/emaillogin?device=$device&token=" $useragent -d "email=$email&password=$password")
    uid=$(echo $logindata|grep -o '\"id\":\"[0-9]*'|cut -d\" -f4)
    token=$(echo $logindata|grep -o '\"token\":\"[a-zA-Z0-9_]*'|cut -d\" -f4)
}
get_vid(){
    curl -s "$base/Videoshow/movietheatre?device=$device&token=$token" $useragent |grep 'vid\|name'|cut -d\" -f4
}
get_m3u8(){
    vid=$1
    echo 'DAUMPLAYLIST' >$vid.dpl
    sidall=$(curl -s "$base/Watch/abstracts?vid=$vid&uid=$uid&device=$device&token=$token" $useragent|grep -o '\"sid\":\"*[0-9]*'|cut -d\" -f4|sed '1d')
    i=0
    for sid in $sidall; do
        sidinfo=$(curl -s "$base/Watch/abstracts?vid=$vid&sid=$sid&uid=$uid&device=$device&token=$token" $useragent)
        sidtitle=$(echo $sidinfo|grep -o '\"vdtitle\":\".*'|cut -d\" -f4)
        sidurl=$(echo $sidinfo|grep -o 'http:\/\/v\.[a-zA-Z0-9_\/\.-]*\.m3u8'|sort -u)
        echo "$sidtitle：$sidurl" >> $vid.txt
        echo "$sidtitle：$sidurl"
        i=$(($i+1))
        echo "$i*file*$sidurl">>$vid.dpl
        echo "$i*title*$sidtitle">>$vid.dpl
    done
    if [ -s "$vid.txt" ]; then
        mv -f $vid.txt ~/app-root/repo/funtown/$vid.txt
        mv -f $vid.dpl ~/app-root/repo/funtown/$vid.dpl
    else
        rm -f $vid.txt
        echo "获取m3u8失败，请确认vid是否正确"
    fi
}

##################
echo "=========欢迎使用方糖工具========="
read -p "是否登录默认账号[yes/no]：" answer
case $answer in
    [nN][oO])
    while true; do
        read -p "请输入邮箱：" email
        email=$(echo $email|sed 's#@#%40#')
        read -p "请输入密码：" password
        login $email $password
        if [ -n "$token" ]; then
            echo "登陆成功！"
            break
        else
            echo "登陆失败！请重新输入"
        fi
    done
    ;;
    *)
    email=$(sed -n '1p' funtown.txt)
    password=$(sed -n '2p' funtown.txt)
    login $email $password
    if [ -n "$token" ]; then
        echo "登陆成功！"
    else
        echo "登陆失败！请修改默认账号密码"
        exit
    fi
    ;;
esac
##################
while true; do
    read -p "请输入视频ID或输入no获取推荐视频ID：" answer
    case $answer in
        [nN][oO])
        get_vid
        ;;
        [0-9][0-9]*)
        get_m3u8 $answer
        ;;
        *)
        break
        ;;
    esac
done